package com.yunbiao.ybbusstopplate.ui.activity

import android.app.ProgressDialog
import android.content.Intent
import android.content.res.Configuration
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.library_hy_advert.HYAdvert
import com.example.library_hy_advert.system.Cache
import com.leon.lfilepickerlibrary.LFilePicker
import com.yunbiao.ybbusstopplate.BuildConfig
import com.yunbiao.ybbusstopplate.R
import com.yunbiao.ybbusstopplate.base.BaseActivity
import com.yunbiao.ybbusstopplate.base.ContentValue
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig
import com.yunbiao.ybbusstopplate.utils.NetController
import com.yunbiao.ybbusstopplate.utils.SSUtils
import com.yunbiao.ybbusstopplate.utils.ScreenPikerUtils
import com.yunbiao.ybbusstopplate.utils.SpTool
import com.yunbiao.ybbusstopplate.utils.cache.LayoutCache
import kotlinx.android.synthetic.main.activity_moresetting.btn_advert_bottom_path_choice
import kotlinx.android.synthetic.main.activity_moresetting.btn_confirm
import kotlinx.android.synthetic.main.activity_moresetting.cb_show_advert
import kotlinx.android.synthetic.main.activity_moresetting.cb_show_time
import kotlinx.android.synthetic.main.activity_moresetting.edit_screen_type_main_address
import kotlinx.android.synthetic.main.activity_moresetting.edt_bus_code
import kotlinx.android.synthetic.main.activity_moresetting.edt_password
import kotlinx.android.synthetic.main.activity_moresetting.edt_user_name
import kotlinx.android.synthetic.main.activity_moresetting.et_serverAddress
import kotlinx.android.synthetic.main.activity_moresetting.et_serverPort
import kotlinx.android.synthetic.main.activity_moresetting.img_advert_bottom_path_clean
import kotlinx.android.synthetic.main.activity_moresetting.imgbtn_back
import kotlinx.android.synthetic.main.activity_moresetting.iv_clear_bus_code
import kotlinx.android.synthetic.main.activity_moresetting.iv_clear_password
import kotlinx.android.synthetic.main.activity_moresetting.iv_clear_user_name
import kotlinx.android.synthetic.main.activity_moresetting.layout_ServerIP
import kotlinx.android.synthetic.main.activity_moresetting.layout_ServerPort
import kotlinx.android.synthetic.main.activity_moresetting.layout_screen_type_main_ip
import kotlinx.android.synthetic.main.activity_moresetting.ll_hy_advert
import kotlinx.android.synthetic.main.activity_moresetting.rb_linetype_full
import kotlinx.android.synthetic.main.activity_moresetting.rb_linetype_loop
import kotlinx.android.synthetic.main.activity_moresetting.rb_online
import kotlinx.android.synthetic.main.activity_moresetting.rb_screen_type_main
import kotlinx.android.synthetic.main.activity_moresetting.rb_screen_type_null
import kotlinx.android.synthetic.main.activity_moresetting.rb_screen_type_sub
import kotlinx.android.synthetic.main.activity_moresetting.rb_standAlone
import kotlinx.android.synthetic.main.activity_moresetting.rg_server
import kotlinx.android.synthetic.main.activity_moresetting.sp_image_time
import kotlinx.android.synthetic.main.activity_moresetting.switch_double_screen
import kotlinx.android.synthetic.main.activity_moresetting.switch_log
import kotlinx.android.synthetic.main.activity_moresetting.tv_advert_bottom_path
import kotlinx.android.synthetic.main.activity_moresetting.tv_deviceNo
import kotlinx.android.synthetic.main.activity_moresetting.tv_server_label
import kotlinx.android.synthetic.main.activity_moresetting.tv_version_setting
import kotlinx.android.synthetic.main.fragment_config.btn_advert_path_choice
import kotlinx.android.synthetic.main.fragment_config.img_advert_path_clean
import kotlinx.android.synthetic.main.fragment_config.sp_serport
import kotlinx.android.synthetic.main.fragment_config.tv_advert_path

class MoreSettingActivity : BaseActivity() {

    private val REQUESTCODE_FROM_ACTIVITY = 110
    private var advertPath = ""//广告本地路径
    private var portType: Int = -1//厂家类型
    private var showAdvert:Boolean=true//显示广告区域
    private var showLineTime:Boolean=false//显示首末班时间
    private var showLineType:Int=1 //线路展示形式 1：全屏 2轮播
    private var screenType:Int = -1
    private var mainScreenAddress:String= "0.0.0.0"

    private var list: ArrayList<String>? = null
    private var typeArray: ArrayList<Int>? = null

    override fun getLayoutViewId(): Int {
        return R.layout.activity_moresetting
    }

    override fun initData() {
        val appVersionName = AppUtils.getAppVersionName()
        tv_version_setting.text = "v$appVersionName"


        tv_deviceNo.text = LayoutCache.getSerNumber()

        initAdvertPath()
        initSerportType()
        initShowConfig()
        initServer()

        initListener()
        initLog();

        checkHYPort(SpTool.getConfigSerialPortType());

        // 隐藏
        btn_advert_path_choice.visibility = View.GONE

        img_advert_path_clean.visibility = View.GONE

        if(btn_advert_bottom_path_choice != null){
            btn_advert_bottom_path_choice?.visibility = View.GONE
        }

        if(img_advert_bottom_path_clean != null){
            img_advert_bottom_path_clean?.visibility = View.GONE
        }

        // 显示 中部广告 本地路径
        tv_advert_path.text = SpTool.getNewLocalAdvertCenterPath()

        // 显示 底部广告 本地路径
        if(tv_advert_bottom_path != null){
            tv_advert_bottom_path?.text = SpTool.getNewLocalAdvertBottomPath()
        }

        initScreenType()

    }
    private fun checkHYPort(portType : Int){
        if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN){
            tv_server_label.visibility = View.GONE
            rg_server.visibility = View.GONE
            ll_hy_advert.visibility = View.VISIBLE
            initHYAdvert()
        } else {
            tv_server_label.visibility = View.VISIBLE
            rg_server.visibility = View.VISIBLE
            ll_hy_advert.visibility = View.GONE
        }
    }
    private fun initHYAdvert(){
        //用户名
        val userName = HYAdvert.getUserName()
        edt_user_name.setText(userName)
        iv_clear_user_name.setOnClickListener {
            edt_user_name.setText("")
        }
        //密码
        val password = HYAdvert.getPassword()
        edt_password.setText(password)
        iv_clear_password.setOnClickListener {
            edt_password.setText("")
        }
        //车号
        val busCode = HYAdvert.getBusCode()
        edt_bus_code.setText(busCode)
        iv_clear_bus_code.setOnClickListener {
            edt_bus_code.setText("")
        }
        //图片播放时长
        val imageTimeIndex = HYAdvert.getImageTimeIndex();
        val intArray = HYAdvert.getImageTimeArray(this)
        val stringArray = arrayOfNulls<String>(intArray.size)
        for (i in stringArray.indices) {
            stringArray[i] = intArray[i].toString() + "秒"
        }
        val adapter: ArrayAdapter<String?> = ArrayAdapter(this, R.layout.myspiner, stringArray)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_image_time.adapter = adapter
        sp_image_time.setSelection(imageTimeIndex)
    }
    private fun saveHYAdvert(){
        HYAdvert.setUserName(edt_user_name.text.toString())
        HYAdvert.setPassword(edt_password.text.toString())
        HYAdvert.setBusCode(edt_bus_code.text.toString())
        HYAdvert.setImageTimeIndex(sp_image_time.selectedItemPosition)
    }
    private fun initLog(){
        val logToFile = SpTool.getLogToFile();
        switch_log.isChecked = logToFile

        val doubleScreen = SpTool.getDoubleScreen()
        switch_double_screen.isChecked = doubleScreen
    }
    private fun initServer(){
        val isOnline = SpTool.getConfigAdvertServerType()
        if (isOnline){
            rb_online.isChecked=true
        }else{
            rb_standAlone.isChecked=true
        }

        rb_online.setOnCheckedChangeListener { compoundButton, b ->
            if (b){
                layout_ServerIP.visibility=View.VISIBLE
                layout_ServerPort.visibility=View.VISIBLE
            }else{
                layout_ServerIP.visibility=View.GONE
                layout_ServerPort.visibility=View.GONE
            }
        }

        val address=SpTool.getServerAddress()
        val port=SpTool.getServerPort()
        et_serverAddress.setText(address)
        et_serverPort.setText(port)
    }

    /**
     * 初始化屏幕类型
     */
    private fun initScreenType() {

        val screenOrdinal = Cache.getInt(Cache.Key.SCREEN_TYPE, -1)
        when(screenOrdinal){
            0-> rb_screen_type_main.isChecked =true
            1-> rb_screen_type_sub.isChecked =true
            -1-> rb_screen_type_null.isChecked =true
        }

        rb_screen_type_sub.setOnCheckedChangeListener { compoundButton, b ->
            if (b){
                layout_screen_type_main_ip.visibility=View.VISIBLE
                screenType = 1
            }else{
                layout_screen_type_main_ip.visibility=View.GONE
            }
        }
        rb_screen_type_main.setOnCheckedChangeListener { compoundButton, b ->
            if (b){
                layout_screen_type_main_ip.visibility=View.VISIBLE
                val ethIpAddress = NetController.getEthIpAddress()
                edit_screen_type_main_address.isEnabled = false
                edit_screen_type_main_address.setText(ethIpAddress)
                screenType = 0
            }else{
                layout_screen_type_main_ip.visibility=View.GONE
            }
        }
        rb_screen_type_null.setOnCheckedChangeListener { compoundButton, b ->
            if (b){
                screenType = -1
            }
        }
       // val screenPosition: Int = binding.spScreenPick.getSelectedItemPosition()

      //  Log.d(Activity.TAG, "screenPosition: $screenPosition") //新选择：0 主屏， 1 副屏
        Log.d("MoreSettingActivity", "screenOrdinal: $screenOrdinal") // 已选择

        // 选择了主屏
        if (rb_screen_type_main.isChecked) {
            val setIsMainScreen = SSUtils.setIsMainScreen()
            Log.d("设置主屏globalFolder: ", setIsMainScreen.toString())
        }

        // 选择了副屏
        if (rb_screen_type_sub.isChecked) {
            val setIsSubScreen = SSUtils.setIsSubScreen()
            mainScreenAddress = SpTool.getMainScreenAddress()
            edit_screen_type_main_address.setText(mainScreenAddress)
            Log.d("设置副屏globalFolder: ", setIsSubScreen.toString())
        }

        // 选择了无副屏
        if (rb_screen_type_null.isChecked) {
            val setIsSubScreen = SSUtils.setNullSubScreen()
            Log.d("设置无副屏globalFolder: ", setIsSubScreen.toString())
        }
//        val address=SpTool.getServerAddress()
//        val port=SpTool.getServerPort()
//        et_serverAddress.setText(address)
//        et_serverPort.setText(port)
    }

    private fun initListener() {
        imgbtn_back.setOnClickListener({
            finish()
        })
        sp_serport.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                if (p2 == 0) {
                    portType = -1
                } else {
                    portType = typeArray!![p2]
                }

                checkHYPort(portType)
            }

        }

        img_advert_path_clean.setOnClickListener({
            advertPath = ""
            tv_advert_path.text = ""
        })

        btn_advert_path_choice.setOnClickListener({
            LFilePicker()
                    .withActivity(this)
                    .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                    .withStartPath(ContentValue.sdPath) //指定初始显示路径
                    .withChooseMode(false) //选择文件夹
                    .withMutilyMode(false)
                    .start()
        })

        btn_confirm.setOnClickListener({
            if (portType == -1) {
                ToastUtils.showShort("请选择报站器厂商")
                return@setOnClickListener
            }
//            ProgressDialogUtils.showProgressDialog(this, "加载配置中，请稍等...")
            showProgressDialog()
            Handler(Looper.getMainLooper()).postDelayed(object : Runnable {
                override fun run() {
                    updateConfig()
                }
            }, 1500)
        })

    }

    private fun updateConfig() {
        //保存图片播放间隔
        if(BuildConfig.FLAVOR_TYPE == FlavorType.LESHAN){
            saveHYAdvert()
        }

        //配置服务器
        SpTool.saveConfigAdvertServerType(rb_online.isChecked)

        val address = et_serverAddress.text.toString().trim()
        val port = et_serverPort.text.toString().trim()
        if (!TextUtils.isEmpty(address)){
            SpTool.saveServerAddress(address)
        }
        if (!TextUtils.isEmpty(port)){
            SpTool.saveServerPort(port)
        }

        val serialPortType = SpTool.getConfigSerialPortType()
        if (portType!=serialPortType){
            SpTool.cleanSiteInfo()
            //清除首末班时间
            SpTool.cleanSiteTime()
        }
        //配置更新
        SpTool.saveConfigSerialPortType(portType)
        SpTool.saveConfigResourcePath(advertPath)

        SpTool.saveConfigShowAdvert(cb_show_advert.isChecked)
        SpTool.saveConfigShowLineTime(cb_show_time.isChecked)

        SpTool.saveDoubleScreen(switch_double_screen.isChecked)

        SpTool.saveLogToFile(switch_log.isChecked)

        //设置屏幕类型
        Cache.setInt(Cache.Key.SCREEN_TYPE, screenType)

        if(ScreenPikerUtils.isSubScreen()){
           if(!TextUtils.isEmpty(edit_screen_type_main_address.text.trim())) {
               mainScreenAddress = edit_screen_type_main_address.text.trim().toString()
               SpTool.saveMainScreenAddress(mainScreenAddress)
           }
        }

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            SpTool.saveConfigShowLineType(1)
        }else{
            if (rb_linetype_full.isChecked){
                SpTool.saveConfigShowLineType(1)
            }else{
                SpTool.saveConfigShowLineType(2)
            }
        }

//        ProgressDialogUtils.dismissProgressDialog()
//        ToastUtils.showShort("设置成功，APP即将重启")
        if (progressDialog!=null){
            progressDialog!!.setMessage("设置成功，APP即将重启")
        }
        //重启app
        Handler(Looper.getMainLooper()).postDelayed(object : Runnable {
            override fun run() {
                if (progressDialog != null) {
                    progressDialog!!.dismiss()
                    progressDialog = null
                }
                AppUtils.relaunchApp(true)
            }

        }, 2000)
    }

    private var progressDialog:ProgressDialog?=null
    private fun showProgressDialog(){
        progressDialog= ProgressDialog(this)
        progressDialog!!.setMessage("正在保存，请稍候...")
        progressDialog!!.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.e("requestCode--->" + requestCode)
        if (requestCode == REQUESTCODE_FROM_ACTIVITY) {
            //选择文件返回
            if (data != null) {
                val filePath = data.getStringExtra("path")
                advertPath = filePath!!
                val path = advertPath.replace(ContentValue.sdPath, "")
                tv_advert_path.text = path
            }
        }
    }

    override fun onDestroy() {
        //隐藏设置dialog
//        EventMsgTool.getInstance().postDismissConfig()
//        ProgressDialogUtils.dismissProgressDialog()
        if (progressDialog!=null){
            progressDialog!!.dismiss()
        }
        super.onDestroy()
    }

    //初始化本地广告储存路径
    private fun initAdvertPath() {
        advertPath=intent.getStringExtra("advertPath")?:""
        if (TextUtils.isEmpty(advertPath)){
            advertPath = SpTool.getConfigResourcePath()
        }
        tv_advert_path.hint = ContentValue.resoucePath
        val path = advertPath.replace(ContentValue.sdPath, "")
        tv_advert_path.text = path
    }
    //初始化报站器类型
    private fun initSerportType() {
        //名称
        list = arrayListOf<String>()
        list!!.add("请选择")
        for (name in SerialPortConfig.PORTNAMES) {
            list!!.add(name)
        }
        //类型
        typeArray = arrayListOf()
        typeArray!!.add(-1)
        for (type in SerialPortConfig.PORTTYPES) {
            typeArray!!.add(type)
        }
        portType=intent.getIntExtra("portType", -1)
        if (portType==-1){
            portType = SpTool.getConfigSerialPortType()
        }
        var index = 0
        if (portType != -1) {
            for (p in typeArray!!) {
                if (p == portType) {
                    break
                }
                index++
            }
        }
        val adapter = ArrayAdapter<String>(this, R.layout.myspiner, list!!)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_serport.adapter = adapter
        sp_serport.setSelection(index)
    }
    //初始化显示相关设置
    private fun initShowConfig(){
        val configShowAdvert = SpTool.getConfigShowAdvert()
        if (configShowAdvert){
            cb_show_advert.isChecked=true
        }else{
            cb_show_advert.isChecked=false
        }

        val configShowLineTime = SpTool.getConfigShowLineTime()
        if (configShowLineTime){
            cb_show_time.isChecked=true
        }else{
            cb_show_time.isChecked=false
        }

        val configShowLineType = SpTool.getConfigShowLineType()
        if (configShowLineType==1){
            rb_linetype_full.isChecked=true
        }else{
            rb_linetype_loop.isChecked=true
        }
    }
}